#encoding=utf-8

import datetime
import time
import urllib
import ujson

from django import forms
from django.contrib import admin
from django.db.models import Count, Max, F, Sum
from django.db.models.query import QuerySet
from django.utils.safestring import mark_safe
from django.utils.html import format_html
from django.contrib.auth.views import login
from django.contrib.auth.models import User,Group
from django.contrib import messages
from andy_manager import settings

from websys.models import (
    UserProfile, HXHUserInfo, HXHPayInfo,PlatformInfo,HXHUserLogin,HXHConsumerInfo,
AgentInfo,UserInfo,GameInfo,RoomInfo,
)
import xadmin
from xadmin.views.list import ResultRow, ResultItem
from websys.admin.AdminLoginForm import AdminAuthenticationForm
from xadmin.views import website
from django.contrib.admin import SimpleListFilter
from xadmin.filters import *#BaseFilter,RelatedFieldListFilter,ListFieldFilter
from django.utils.translation import ugettext_lazy as _
from django.db.models.fields.related import ForeignKey
from django.utils.encoding import smart_unicode

class MyRelate(ListFieldFilter):
    title = _('testID')
    lookup_exact_val=''
    lookup_isnull_val='True'

    def choices(self):
        yield {
            'selected': self.lookup_exact_val == '' and not self.lookup_isnull_val,
            'query_string': self.query_string({},
                                              [self.lookup_exact_name, self.lookup_isnull_name]),
            'display': _('All'),
        }
        for pk_val, val in self.lookup_choices:
            yield {
                'selected': self.lookup_exact_val == smart_unicode(pk_val),
                'query_string': self.query_string({
                    self.lookup_exact_name: pk_val,
                }, [self.lookup_isnull_name]),
                'display': val,
            }


class AgentFilter(BaseFilter):
    title = _('直属代理')
    template = 'xadmin/filters/list.html'
    lookup_isnull_val='True'
    lookup_isnull_name=''
    lookup_exact_val='0'
    lookup_choices=[]

    def __init__(self, request, params, model, admin_view,_lookup_exact_name='_p_parentid__id__exact',_field_path='parentid'):
        self.lookup_exact_name=_lookup_exact_name#'_p_parentid__id__exact'
        self.field_path=_field_path#'parentid'

        self.used_params = {}
        self.request = request
        self.params = params
        self.model = model
        self.admin_view = admin_view
        #self.lookup_choices=[(10L, u'c(cc)'), (11L, u'c1(c1)'), (12L, u'c2(c2)'), (13L, u'b25(b25)'), (14L, u'd(ddddd)'), (15L, u'd2(d2)')]
        #根据登陆者获取对应的代理列表
        my_choices=[]
        login_uid = request.user.username
        parcid='1'
        isshow_blank=False
        if AgentInfo.objects.filter(account=login_uid).exists():#是代理
            a_info=AgentInfo.objects.get(account=login_uid)
            parcid=a_info.classid
        else:
            isshow_blank=True
        #print(parcid,'----__init__,,,,,,,,,,,,,,,,,,,,,,,--',isshow_blank)
        qs = AgentInfo.objects.filter(classid__startswith=parcid).values("id","account","username")
        for item in qs:
            my_choices.append((item['id'],item['account']))
        self.lookup_choices=my_choices

        super(AgentFilter,self)

        self.context_params = {}
        #self.lookup_formats = {'in': '%%s__%s__in' % rel_name,'exact': '%%s__%s__exact' % rel_name, 'isnull': '%s__isnull'}
        self.lookup_formats = {'isnull': '%s__isnull', 'exact': u'%s__id__exact', 'in': u'%s__id__in'}
        #是否显示空的下拉
        self.show_blank=isshow_blank

        for name, format in self.lookup_formats.items():
            p = format % self.field_path
            self.context_params["%s_name" % name] = FILTER_PREFIX + p
            if p in params:
                value = prepare_lookup_value(p, params.pop(p))
                self.used_params[p] = value
                self.context_params["%s_val" % name] = value
            else:
                self.context_params["%s_val" % name] = ''

        map(lambda kv: setattr(
            self, 'lookup_' + kv[0], kv[1]), self.context_params.items())

    #重写过滤的方法
    def do_filte(self, queryset):#
        #print(queryset,'---do_filte*****',dir(queryset))#当前页面的数据
        return queryset.filter(**self.used_params)

    def has_output(self):
        return True

    def choices(self):
        #全部
        yield {
            'selected': self.lookup_exact_val == '' and not self.lookup_isnull_val,
            'query_string': self.query_string({},
                                              [self.lookup_exact_name, self.lookup_isnull_name]),
            'display': _('All'),
        }
        #列表
        for pk_val, val in self.lookup_choices:
            yield {
                'selected': self.lookup_exact_val == smart_unicode(pk_val),
                'query_string': self.query_string({
                    self.lookup_exact_name: pk_val,
                }, [self.lookup_isnull_name]),
                'display': val,
            }
        #空的
        if self.show_blank:
            yield {
                    'selected': bool(self.lookup_isnull_val),
                    'query_string': self.query_string({
                        self.lookup_isnull_name: 'True',
                    }, [self.lookup_exact_name]),
                    'display': EMPTY_CHANGELIST_VALUE,
                }


    def get_context(self):
        context = super(AgentFilter, self).get_context()
        context['choices'] = list(self.choices())
        #print context,'************get_context***************'
        return context

    def queryset(self, request, queryset):

        return queryset.filter(book_id=request.GET['userId'])

class UserFilter(BaseFilter):
    title = _('玩家帐号')
    template = 'xadmin/filters/list.html'
    lookup_isnull_val='True'
    lookup_isnull_name=''
    lookup_exact_val='0'
    lookup_choices=[]

    def __init__(self, request, params, model, admin_view,_lookup_exact_name='_p_uid__id__exact',_field_path='uid'):
        self.lookup_exact_name=_lookup_exact_name#'_p_parentid__id__exact'
        self.field_path=_field_path#'parentid'

        self.used_params = {}
        self.request = request
        self.params = params
        self.model = model
        self.admin_view = admin_view
        #self.lookup_choices=[(10L, u'c(cc)'), (11L, u'c1(c1)'), (12L, u'c2(c2)'), (13L, u'b25(b25)'), (14L, u'd(ddddd)'), (15L, u'd2(d2)')]
        #根据登陆者获取对应的代理列表
        my_choices=[]
        login_uid = request.user.username
        parcid='1'
        isshow_blank=False
        if AgentInfo.objects.filter(account=login_uid).exists():#是代理
            a_info=AgentInfo.objects.get(account=login_uid)
            parcid=a_info.classid
            qs = UserInfo.objects.filter(agentid__classid__startswith=parcid).values("id","nickname")
        else:
            isshow_blank=True
            qs = UserInfo.objects.values("id","nickname")

        for item in qs:
            my_choices.append((item['id'],item['nickname']))
        self.lookup_choices=my_choices

        super(UserFilter,self)

        self.context_params = {}
        #self.lookup_formats = {'in': '%%s__%s__in' % rel_name,'exact': '%%s__%s__exact' % rel_name, 'isnull': '%s__isnull'}
        self.lookup_formats = {'isnull': '%s__isnull', 'exact': u'%s__id__exact', 'in': u'%s__id__in'}
        #是否显示空的下拉
        self.show_blank=isshow_blank

        for name, format in self.lookup_formats.items():
            p = format % self.field_path
            self.context_params["%s_name" % name] = FILTER_PREFIX + p
            if p in params:
                value = prepare_lookup_value(p, params.pop(p))
                self.used_params[p] = value
                self.context_params["%s_val" % name] = value
            else:
                self.context_params["%s_val" % name] = ''

        map(lambda kv: setattr(
            self, 'lookup_' + kv[0], kv[1]), self.context_params.items())

    #重写过滤的方法
    def do_filte(self, queryset):#
        #print(queryset,'---do_filte*****',dir(queryset))#当前页面的数据
        return queryset.filter(**self.used_params)

    def has_output(self):
        return True

    def choices(self):
        #全部
        yield {
            'selected': self.lookup_exact_val == '' and not self.lookup_isnull_val,
            'query_string': self.query_string({},
                                              [self.lookup_exact_name, self.lookup_isnull_name]),
            'display': _('All'),
        }
        #列表
        for pk_val, val in self.lookup_choices:
            yield {
                'selected': self.lookup_exact_val == smart_unicode(pk_val),
                'query_string': self.query_string({
                    self.lookup_exact_name: pk_val,
                }, [self.lookup_isnull_name]),
                'display': val,
            }
        #空的
        if self.show_blank:
            yield {
                    'selected': bool(self.lookup_isnull_val),
                    'query_string': self.query_string({
                        self.lookup_isnull_name: 'True',
                    }, [self.lookup_exact_name]),
                    'display': EMPTY_CHANGELIST_VALUE,
                }


    def get_context(self):
        context = super(UserFilter, self).get_context()
        context['choices'] = list(self.choices())
        #print context,'************get_context***************'
        return context

    def queryset(self, request, queryset):

        return queryset.filter(book_id=request.GET['userId'])

class DecadeBornListFilter(BaseFilter):
	# Human-readable title which will be displayed in the
	# right admin sidebar just above the filter options.
	title = _('decade born')

	# Parameter for the filter that will be used in the URL query.
	parameter_name = 'decade'

	def lookups(self, request, model_admin):
		"""
		Returns a list of tuples. The first element in each
		tuple is the coded value for the option that will
		appear in the URL query. The second element is the
		human-readable name for the option that will appear
		in the right sidebar.
		"""
		return (
			('80s', _('in the eighties')),
			('90s', _('in the nineties')),
		)
xadmin.filters.manager.register(DecadeBornListFilter)
xadmin.filters.manager.register(AgentFilter)
xadmin.filters.manager.register(UserFilter)